import fs = require('fs')
import path = require('path')


export default class CodeReader {

    constructor(
        private dir = ``,
        private callback: (line: string) => void,
        private checkAvailable: ((name: string) => boolean) | undefined
    ) {
        this.readProject(this.dir)
    }

    private readProject(dir: string) {
        const filenames = fs.readdirSync(dir)
        for (let name of filenames) {
            const filePath = `${dir}/${name}`
            const stat = fs.statSync(filePath)
            var isStartComment = false
            var isEndComment = false
            if (stat.isDirectory()) {
                this.readProject(filePath)
            } else if (stat.isFile() && this.isAvailable(name)) {
                const content = fs.readFileSync(filePath, {encoding: "utf-8"})
                const lines = content.split('\n')
                lines.filter(l => {
                    l = l.trim()
                    if (!isStartComment && l.startsWith("/*")) {
                        isStartComment = true
                    }
                    if (!isEndComment && l.endsWith("*/")){
                        isEndComment = true
                    }
                    return !isStartComment && !isEndComment && l.length > 0 && !l.startsWith("//")
                }).forEach((s) => this.callback(s.trim()))
            }
        }
    }

    private isAvailable(name: string) {
        if (name.search(/\./) == 0) {
            return false
        }
        if (this.checkAvailable) {
            return this.checkAvailable(name)
        } else {
            return false
        }
    }
}